package com.ltu.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ltu.domain.mp_entity.OrderDetailEntity;
import com.ltu.domain.mp_entity.OrderEntity;
import com.ltu.domain.mp_entity.PayRecord;
import com.ltu.domain.mp_entity.UserEntity;
import com.ltu.domain.mp_entity.customize.CompanyEntity;
import com.ltu.domain.mp_entity.customize.WalletRecordEntity;
import com.ltu.enums.MqTopiceDict;
import com.ltu.enums.OrderEnums;
import com.ltu.mapper.OrderMapper;
import com.ltu.model.request.order.PlaceOrderReq;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.myannotation.MyReidsCache;
import com.ltu.payment.PubPayService;
import com.ltu.payment.enums.PayWayDict;
import com.ltu.service.OrderDetailService;
import com.ltu.service.OrderService;
import com.ltu.service.PayRecordService;
import com.ltu.service.UserService;
import com.ltu.service.customize.WalletRecordService;
import com.ltu.service.mqtt.MqttPushClient;
import com.ltu.util.common.StrUtils;
import com.ltu.util.datetime.DateUtils;
import com.ltu.util.ext.qrcode.QRCodeUtil;
import com.ltu.util.ext.wx.wxPay.ServletUtil;
import com.ltu.util.redis.RedisKeyManager;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 设备续费订单 服务实现类
 * </p>
 *
 * @author 若尘
 * @since 2022-02-21
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, OrderEntity> implements OrderService {
	private final PayRecordService payRecordService;
	private final UserService userService;
	private final PubPayService pubPayService;
	private final MqttPushClient mqttPushClient;
	private final OrderDetailService  orderDetailService;
	private final WalletRecordService  walletRecordService;
	@Value("${payInfo.test}")
    private Integer PayTest = 1;

	private void sendToDlayedTopic( String payload) {
		log.info("订单写入回调消息队列");
		Object[] param = new Object[2];
		param[0]="180";
		param[1]=MqTopiceDict.OrderEnum.OrderPayListen.getValue();
		String fullTopic =	String.format(MqTopiceDict.DelayedPrefix, param);
		mqttPushClient.pushlish(fullTopic,payload);
	}
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public CodeDataResp<JSONObject> placeOrder(	OrderEntity order,PayWayDict dict) {
		String ip  = ServletUtil.getCurrentRequestIp();
		order.setPayStatus((byte) 2);
	
		JSONObject result=null;
		try {
			order.setPayWay(dict.getIndex());
			this.updateById(order);
//			UserEntity userEntity = userService.getById(order.getUserId());
			//创建PayRecord
			PayRecord payRecord = createOrderPayRecord(order);
			this.updateById(order);
			result = pubPayService.placeOrder(payRecord, order.getOpenid(), ip);
			result.put("orderId", order.getId());
		} catch (Exception e) {
			order.setPayStatus((byte)0);
			this.updateById(order);
			throw e;
		}
		return CodeDataResp.valueOfSuccess(result);
	}
	
	private  PayRecord createOrderPayRecord(OrderEntity order) {
		PayRecord payRecord = null;
		QueryWrapper< PayRecord > wrapper = new QueryWrapper<PayRecord>();
		wrapper.orderByDesc("id");
		wrapper.lambda() .eq(PayRecord :: getOrderId, order.getId())
						.last("limit 1"); 
		payRecord =		this.payRecordService.getOne(wrapper);
		Date currentDate = new Date();
		StringBuilder sb = new StringBuilder("D");
		sb.append(DateUtils.format(currentDate, DateUtils.DATE_TIME_FORMAT_NUMBER))
				.append(StrUtils.generateZeroCharacter(order.getUserId().toString(), 6, "0"))
				.append("0")
				.append(StrUtils.randomnum(999, 99999));
		if(payRecord != null ) {
			payRecord.setOrderNo(sb.toString());
			payRecord.setStatus((byte)2);
			this.payRecordService.updateById(payRecord);
			return payRecord;
	}
		payRecord= new PayRecord();
		payRecord.setCreateTime(order.getCreateTime())
				 .setOrderId(Integer.parseInt(order.getId()))
				 .setOpenId(order.getOpenid())
				 .setOrderNo(sb.toString())
				 .setPayMoney(order.getPayableFee())
				 .setPayWay(order.getPayWay())
				 .setUserId(order.getUserId())
				 .setStatus((byte)2)
				 .setPayName(order.getSourceDesc())
				;
		payRecordService.save(payRecord);
		order.setPayRecordId(Integer.parseInt(payRecord.getId()));
		return payRecord;
	}

	/**
	 * 创建订单
	 */
	public OrderEntity createOrder(OrderEnums.OrderSource dict,String productNames ,UserEntity userEntity,Integer totalFee,String sourceIds) {
		Date currentDate = new Date();
		StringBuilder sb = new StringBuilder("D");
		sb.append(DateUtils.format(currentDate, DateUtils.DATE_TIME_FORMAT_NUMBER))
				.append(StrUtils.generateZeroCharacter(userEntity.getId(), 6, "0"))
				;
		OrderEntity order = new OrderEntity();
		order.setUserId(Integer.parseInt(userEntity.getId()))
			.setUserName(userEntity.getNickName())
			.setOrderNo(sb.toString())
			.setTotalFee(totalFee)
			.setCreateTime(currentDate);
		order.setSourceDict(dict.getIndex())
		.setSourceDesc(dict.getName().concat(":").concat(productNames))
		.setPayWay((byte) 5)
		.setSourceIds(sourceIds)
		.setPayableFee(PayTest == 1?1:order.getTotalFee())
		.setTotalFee(totalFee)
		.setOpenid(userEntity.getOpenId())
		;
		this.save(order);
		return order;
	}





 
}
